package com.bicon.botu.account.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.account.common.AccountConstants;
import com.bicon.botu.account.dto.ResourcesDto;
import com.bicon.botu.account.entity.Role;
import com.bicon.botu.account.entity.RoleResources;
import com.bicon.botu.account.mapper.RoleResourcesMapper;
import com.bicon.botu.account.service.IRoleResourcesService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.NodeUtil;
import com.bicon.botu.core.base.common.utils.StringUtils;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @auther 裴志鹏
 * @date 2017/11/30 11:37
 */
@Slf4j
@Service
public class RoleResourcesServiceImpl extends ServiceImpl<RoleResourcesMapper, RoleResources> implements IRoleResourcesService {

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    private RoleResourcesMapper roleResourcesMapper;

    /**
     * 增加角色资源关联
     *
     * @param roleId      角色Id
     * @param resourceIds 资源id,可多个一起传。双井号隔开“##”
     * @param type        账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult saveRoleResourceIds(String roleId, String[] resourceIds, String type) {
        List<RoleResources> roleResourcesList = new ArrayList<>();
        for (int i = 0; i < resourceIds.length; i++) {
            RoleResources roleResources = new RoleResources();
            roleResources.setResourcesId(resourceIds[i]);
            roleResources.setRoleId(roleId);
            roleResources.preInsert();
            roleResources.setType(type);
            roleResourcesList.add(roleResources);
        }
        insertBatch(roleResourcesList);
//      添加redis缓存
        if ("0".equals(type)) {
//          校验key是否存在
            List<String> pathList = new ArrayList<>();
            for (int i = 0; i < resourceIds.length; i++) {
                pathList.add(resourceIds[i]);
            }
            if (redisHandler.getGlobalRedisTemplate().hasKey(AccountConstants.ROLE_RESOURCES + roleId)) {
                List<String> list = redisHandler.getGlobalRedisTemplate().getList(AccountConstants.ROLE_RESOURCES, roleId);
                redisHandler.getGlobalRedisTemplate().remove(AccountConstants.ROLE_RESOURCES, roleId);
                list.addAll(pathList);
//              对list去重
                HashSet hashSet = new HashSet(list);
                list.clear();
                list.addAll(hashSet);
                redisHandler.getGlobalRedisTemplate().cacheList(AccountConstants.ROLE_RESOURCES, roleId, list);
            } else {
                redisHandler.getGlobalRedisTemplate().cacheList(AccountConstants.ROLE_RESOURCES, roleId, pathList);
            }
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }


    /**
     * 删除角色资源
     *
     * @param roleId 角色ID
     * @param type   账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult deleteRoleResourcesByRoleId(String roleId, String type) {
        RoleResources roleResources = new RoleResources();
        roleResources.preUpdate();
        roleResources.setLogicDelete(Constants.DEL_LOGIC_DELETE);
        boolean result = roleResources.update(new EntityWrapper<RoleResources>().eq("type", type).eq("role_id", roleId));
        if (result) {
            if ("0".equals(type)) {
                redisHandler.getGlobalRedisTemplate().remove(AccountConstants.ROLE_RESOURCES, roleId);
            }
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        } else {
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
    }

    /**
     * 查询角色下的资源(树形结构)
     *
     * @param roleId 角色Id
     * @param type   账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult findRolesResources(String roleId, String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("roleId", roleId);
        map.put("type", type);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        List<ResourcesDto> resources = roleResourcesMapper.findResourcesByRoleId(map);
        if ("1".equals(type)) {
            List<ResourcesDto> resultList = new NodeUtil<ResourcesDto>().getChildNodes(resources);
            if (resultList.size() > 0) {
                return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, resultList);
            }
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, resources);
    }

    @Override
    public BaseResult initRoleResources() {
        List<Role> roleList = new Role().selectList(new EntityWrapper<Role>().eq("type", "0").eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        for (Role role : roleList) {
            redisHandler.getGlobalRedisTemplate().remove(AccountConstants.ROLE_RESOURCES, role.getId());
            //放入资源
            Map<String, Object> map = new HashMap<>();
            map.put("roleId", role.getId());
            map.put("type", "0");
            map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
            List<ResourcesDto> resourcesList = roleResourcesMapper.findResourcesByRoleId(map);
            List<String> pathList = new ArrayList<>();
            for (ResourcesDto resources : resourcesList) {
                if (StringUtils.isNotEmpty(resources.getPath())){
                    pathList.add(resources.getPath());
                }
            }
            if (pathList != null && pathList.size() > 0) {
                redisHandler.getGlobalRedisTemplate().cacheList(AccountConstants.ROLE_RESOURCES, role.getId(), pathList);
            }
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }
}
